from PIL import Image
from PIL import ImageDraw
import sys
import os
import subprocess
# 使用pillow读取图片，获取图片的宽和高
def read_img(image_path):
	img = {}
	xml = []
	status = 0
	img_pillow = Image.open(image_path)

	img['width'] = img_pillow.width # 图片宽度
	img['height'] = img_pillow.height # 图片高度
	return img


base=sys.argv[1]
#遍历图片目录创建文件列表
#eg：python imgwh.py images/
file_list = []
for line in os.listdir(base):
    file_list.append(line)

print(file_list)

xml_path="%s/xml"%base
try:
    for line in os.listdir(xml_path):
        os.remove("%s/%s"%(xml_path,line))
    os.rmdir(xml_path)
except:
    pass
os.mkdir(xml_path,0o775);
img_wh = {}
for line in file_list:
    image_path = "%s/%s"%(base,line)
    print(image_path)
    img_wh['width'] = 0
    img_wh['height'] = 0
    img_wh = read_img(image_path)
    fo = open("%s/%s.xml"%(xml_path,line[:-4]), "w")
    fo.write("\
<annotation>\n\
    <folder>images</folder>\n\
    <filename>%s</filename>\n\
    <size>\n\
        <width>%s</width>\n\
        <height>%s</height>\n\
        <depth>3</depth>\n\
    </size>\n\
    <segmented>0</segmented>\n\
    <object>\n\
        <name>tube</name>\n\
        <pose>Unspecified</pose>\n\
        <truncated>0</truncated>\n\
        <occluded>0</occluded>\n\
        <difficult>0</difficult>\n\
        <bndbox>\n\
            <xmin>0</xmin>\n\
            <ymin>0</ymin>\n\
            <xmax>0</xmax>\n\
            <ymax>0</ymax>\n\
        </bndbox>\n\
    </object>\n\
</annotation>\n"%(line,img_wh['width'],img_wh['height']))
fo.close()
